package com.block.job.service;

import com.block.common.exception.NotifyExceptionService;
import com.block.common.service.LogFactory;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Component
public class QueryBillsJob {

    private static final Logger log = LogFactory.getJobLog();

    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;


    @Autowired
    NotifyExceptionService notifyExceptionService;

    /**
     * 查询成功率
     *
     * @throws Exception
     */
    @XxlJob("QueryBillsJob")
    public void query() throws Exception {
        XxlJobHelper.log("查询每天商户失败率---------开始执行--------");

        List<Map<String, Object>> dataList = sourcePushResultInfoMapper.selectQuerBills();

        StringBuilder message = new StringBuilder();
        message.append("查询机构失败率：\n");

        for (Map<String, Object> data : dataList) {
            String name = (String) data.get("name");
            String ownerName = (String) data.get("ownerName");
            int success = ((BigDecimal) data.get("success")).intValue();
            if (success == 0) {
                continue;
            }
            int fail = ((BigDecimal) data.get("fail")).intValue();
            BigDecimal total = new BigDecimal(success + fail);
            double successRate = total.equals(BigDecimal.ZERO) ? 0 : success / total.doubleValue() * 100;

            // 只发送成功率小于85%的数据
            if (successRate < 85) {
                double failRate = total.equals(BigDecimal.ZERO) ? 0 : fail / total.doubleValue() * 100;
                message.append("机构名称: ").append(name).append("\n");
                message.append("商务信息: ").append(ownerName).append("\n");
                message.append("   - 成功次数: ").append(success).append("\n");
                message.append("   - 失败次数: ").append(fail).append("\n");
                message.append("   - 成功率: ").append(String.format("%.2f%%", successRate)).append("\n");
                message.append("   - 失败率: ").append(String.format("%.2f%%", failRate)).append("\n");
            }
        }
        // 将消息通知发送到企业微信
        notifyExceptionService.notifyWechatShibaiException("MERCHANT_NOTICE", "", message.toString(), null);
    }
}
